//
//  QMCameraViewController.m
//  QMCamera
//
//  Created by guoqingwei on 16/7/20.
//  Copyright © 2016年 cvte. All rights reserved.
//

#import "QMCameraViewController.h"
#import "SLCameraHelper.h"
#import "QMCameraPreview.h"
#import "QMLibManager.h"
#import "MultiSelectViewController.h"
#import "ViewUtils.h"
#import "ImageViewController.h"
#import "MultiSelectViewController.h"


static const CGFloat kToolBarHeight = 100.f;
static const CGFloat kDetectInterval = 1.f;

@interface QMCameraViewController () <SLCameraTakePhotoDelegate, QMLibManagerDelegate>

@property (nonatomic, strong) QMCameraPreview *cameraView;
@property (nonatomic, strong) SLCameraHelper *cameraHelper;
@property (nonatomic, strong) QMLibManager *libManager;
@property (strong, nonatomic) UILabel *errorLabel;
@property (strong, nonatomic) UIButton *snapButton;
@property (strong, nonatomic) UIButton *switchButton;
@property (strong, nonatomic) UIButton *flashButton, *questionButton;
@property (strong, nonatomic) UISegmentedControl *segmentedControl;
@property (strong, nonatomic) UIImageView *images;
@property (strong, nonatomic) UIImage *uploadImage;
@property (strong, nonatomic) NSMutableArray *uploadImages;

@property (nonatomic, strong) UIImage *beforeImage;
@property (nonatomic, strong) UIImage *afterImage;
@end

@implementation QMCameraViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
        
    self.view.backgroundColor = [UIColor blackColor];

    self.cameraView = [[QMCameraPreview alloc] initWithFrame:self.view.bounds];
    
    [self.view addSubview:self.cameraView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadSuccess) name:@"UploadSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadSuccess) name:@"UploadSuccess2" object:nil];
    
    
    [self initView];
}

- (void)initView{
    // ----- camera buttons -------- //
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    // snap button to capture image
    self.snapButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.snapButton.frame = CGRectMake(0, 0, 70.0f, 70.0f);
    self.snapButton.clipsToBounds = YES;
    self.snapButton.layer.cornerRadius = self.snapButton.width / 2.0f;
    self.snapButton.layer.borderColor = [UIColor whiteColor].CGColor;
    self.snapButton.layer.borderWidth = 2.0f;
    self.snapButton.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
    self.snapButton.layer.rasterizationScale = [UIScreen mainScreen].scale;
    self.snapButton.layer.shouldRasterize = YES;
    [self.snapButton addTarget:self action:@selector(snapButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.snapButton];
    
    
    // button to close view
    self.switchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.switchButton.frame = CGRectMake(0, 0, 29.0f + 30.0f, 22.0f + 30.0f);
    self.switchButton.tintColor = [UIColor whiteColor];
    [self.switchButton setImage:[UIImage imageNamed:@"cancel.png"] forState:UIControlStateNormal];
    self.switchButton.imageEdgeInsets = UIEdgeInsetsMake(10.0f, 10.0f, 10.0f, 10.0f);
    [self.switchButton addTarget:self action:@selector(switchButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.switchButton];
    
    
    // button to close view
    self.questionButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.questionButton.frame = CGRectMake(0, 0, 29.0f + 30.0f, 22.0f + 30.0f);
    self.questionButton.tintColor = [UIColor whiteColor];
    [self.questionButton setTitle:@"拍摄说明" forState:UIControlStateNormal];
    self.questionButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.questionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.questionButton addTarget:self action:@selector(questionButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.questionButton];
    
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"单张",@"批量"]];
    self.segmentedControl.frame = CGRectMake(12.0f, screenRect.size.height - 67.0f, 120.0f, 32.0f);
    if([_selectType isEqualToString:@"single"]){
        self.segmentedControl.selectedSegmentIndex = 0;
    }else{
        self.segmentedControl.selectedSegmentIndex = 1;
    }
    self.segmentedControl.tintColor = [UIColor whiteColor];
    [self.segmentedControl addTarget:self action:@selector(segmentedControlValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentedControl];
    
    
    self.images = [[UIImageView alloc] init];
    self.images.frame = CGRectMake(0, 0, 70, 70);
    self.images.userInteractionEnabled = YES;
    self.images.contentMode = UIViewContentModeScaleAspectFill;
    self.images.clipsToBounds = YES;
    UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTaped)];
    [self.images addGestureRecognizer:imageTap];
    [self.view addSubview:self.images];
    if([self.selectType isEqualToString:@"single"]){
        self.images.hidden = YES;
    }else{
        self.images.hidden = NO;
    }
    
    self.cameraHelper = [SLCameraHelper sharedInstance];
    self.cameraHelper.photodelegate = self;
    
    self.libManager = [QMLibManager sharedInstance];
    self.libManager.delegate = self;
    
    [self checkCameraAuthorized];

}

- (void)uploadSuccess {
    [self dismissViewControllerAnimated:NO completion:nil];
}


- (void)imageTaped{
    
    if(self.uploadImages.count > 0){
        MultiSelectViewController *vc = [[MultiSelectViewController alloc] init];
        vc.images = [NSMutableArray arrayWithArray:self.uploadImages];
        vc.exerciseUid = self.exerciseUid;
        __weak typeof(self) weakSelf = self;
        vc.deletBlock = ^(NSMutableArray *images){
            weakSelf.uploadImages = images;
            if(weakSelf.uploadImages.count > 0){
                [weakSelf.images addBadgeTipWithPopAnimation:[NSString stringWithFormat:@"%lu",(unsigned long)weakSelf.uploadImages.count]];
                weakSelf.images.image = [weakSelf.uploadImages firstObject];
                weakSelf.images.hidden = NO;
            }else{
                [weakSelf.images removeBadgeTips];
                weakSelf.images.hidden = YES;
            }
        };
        [self presentViewController:vc animated:NO completion:nil];
    }
    
}


- (void)segmentedControlValueChanged:(UISegmentedControl *)control
{
    if(control.selectedSegmentIndex == 0){
        self.selectType = @"single";
        self.images.hidden = YES;
    }else{
        self.selectType = @"multi";
        self.images.hidden = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [self.cameraHelper insertSublayerWithCaptureView:self.cameraView atRootView:self.view];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.libManager.detectSize = self.view.bounds.size;
    [self.cameraHelper startRunning];
    [self.libManager startDetect:kDetectInterval];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self.libManager stopDetect];
    [self.cameraHelper stopRunning];
}



/* camera button methods */

- (void)switchButtonPressed:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (void)questionButtonPressed:(UIButton *)button{
    NSMutableArray *images = [NSMutableArray array];
    [images addObject:[UIImage imageNamed:@"intro1"]];
    [images addObject:[UIImage imageNamed:@"intro2"]];
    [images addObject:[UIImage imageNamed:@"intro3"]];
    MultiSelectViewController *vc = [[MultiSelectViewController alloc] init];
    vc.images = images;
    vc.toShow = YES;
    [self presentViewController:vc animated:NO completion:nil];
}



- (void)snapButtonPressed:(UIButton *)button
{

    if ([self.cameraView inPreview]) {
        [self.cameraView setPreviewImage:nil];
        self.beforeImage = nil;
        self.afterImage = nil;
        [self.libManager startDetect:kDetectInterval];
    } else {
        [self.libManager stopDetect];
        [self.cameraHelper takePhotoWithOrientation:[UIDevice currentDevice].orientation cropSize:self.view.bounds.size];
    }
    
    
}

/* other lifecycle methods */

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    self.cameraView.frame = self.view.bounds;
    [self.cameraHelper updatePreviewLayer];
    
    self.questionButton.center = self.view.contentCenter;
    self.questionButton.top = 5.0f;
    self.questionButton.left = 10.0f;
    
    self.snapButton.center = self.view.contentCenter;
    self.snapButton.bottom = self.view.height - 15.0f;
    
    self.images.center = self.view.contentCenter;
    self.images.bottom = self.view.height - 15.0f;
    self.images.right = self.view.width - 30.0f;
    
    self.flashButton.center = self.view.contentCenter;
    self.flashButton.top = 5.0f;
    
    self.switchButton.top = 3.0f;
    self.switchButton.right = self.view.width - 5.0f;
    
    self.segmentedControl.left = 12.0f;
    self.segmentedControl.bottom = self.view.height - 35.0f;
}




- (BOOL)shouldAutorotate
{
    return NO;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}



#pragma mark - SLCameraHelperDelegate

- (void)cameraDidTakePhoto:(UIImage *)stillImage
{
    self.beforeImage = stillImage;
    
    
    [self.libManager enhanceCommonImage:self.beforeImage];
}

#pragma mark - QMLibManagerDelegate

- (void)libManager:(QMLibManager *)manager didSuccessDetectPoints:(NSArray *)points
{
    [self.cameraView drawDetectionEdgeWithPoints:points];
}

- (void)libManagerDidFailDetect:(QMLibManager *)manager
{
    [self.cameraView clearDetectionEdge];
}

- (void)libManager:(QMLibManager *)manager didReceiveEnhanceResult:(UIImage *)resultImage
{
    self.afterImage = resultImage;

    
    if([self.selectType isEqualToString:@"single"]){
        

        ImageViewController *imageVC = [[ImageViewController alloc] initWithImage:self.afterImage];
        imageVC.exerciseUid = self.exerciseUid;
        imageVC.studentUid = self.studentUid;
        [self presentViewController:imageVC animated:NO completion:nil];
        
        
    }else{
        if(!self.uploadImages){
            self.uploadImages = [NSMutableArray array];
        }

        [self.uploadImages addObject:self.afterImage];
        self.images.image = self.afterImage;
        if(self.uploadImages.count > 0){
            [self.images addBadgeTipWithPopAnimation:[NSString stringWithFormat:@"%lu",(unsigned long)self.uploadImages.count]];
        }else{
            [self.images removeBadgeTips];
        }
        
    }
    
    

}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Private methods

- (void)beforeProcessButtonTapped
{
    [self.cameraView setPreviewImage:self.beforeImage];
}



- (void)afterProcessButtonTapped
{
    [self.cameraView setPreviewImage:self.afterImage];
}

- (void)backClicked:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGRect)frameForToolBarWithVerticalLayout:(BOOL)verticalLayout
{
    CGRect frame = CGRectZero;
    if (verticalLayout) {
        frame.origin.x = 0.0f;
        frame.origin.y = CGRectGetHeight(self.view.bounds) - kToolBarHeight;
        frame.size.width = CGRectGetWidth(self.view.bounds);
        frame.size.height = kToolBarHeight;
    } else {
        frame.origin.x = CGRectGetWidth(self.view.bounds) - kToolBarHeight;
        frame.origin.y = 0.0f;
        frame.size.width = kToolBarHeight;
        frame.size.height = CGRectGetHeight(self.view.bounds);
    }
    return frame;
}

- (void)checkCameraAuthorized
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (authStatus) {
        case AVAuthorizationStatusAuthorized:
            break;
        case AVAuthorizationStatusDenied:
        case AVAuthorizationStatusRestricted:
        {
            [self showAlertMessage:@"没有相机权限"];
            break;
        }
        case AVAuthorizationStatusNotDetermined:
        {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (!granted) {
                    [self showAlertMessage:@"没有相机权限"];
                }
            }];
            break;
        }
        default:
            [self showAlertMessage:@"没有相机权限"];
            break;
    }
}

- (void)showAlertMessage:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                        message:message
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
}


@end
